<template>
<div>
    <Affix :offset-top="50">
        <Row class="topBtnDiv">
            <Col>
            <Button type="primary" icon="android-done" @click="Publish">生成系统模块</Button>
            <Button type="dashed" icon="refresh" @click="RollBack">恢复系统模块</Button>
            </Col>
        </Row>
    </Affix>
    <Row style="margin-top:20px">
        <Col>
        <div id="SystemModules"></div>
        </Col>
    </Row>

    <Modal v-model="Form.IsShow" :loading="Form.IsLoading" :title="Form.Title" @on-ok="Form.OkEvent" @on-cancel="Form.CancelEvent">
        <Form ref="EditForm" :model="Form.Data" label-position="top">
            <Row :gutter="16">
                <Col :xs="24" :md="12">
                <FormItem label="模块名称" prop="Name" :rules="{required: true, message:'不能为空', trigger: 'blur'}">
                    <Input v-model="Form.Data.Name"></Input>
                </FormItem>
                </Col>

                <Col :xs="24" :md="12">
                <FormItem label="模块备注" prop="Remark">
                    <Input v-model="Form.Data.Remark"></Input>
                </FormItem>
                </Col>

                <Col :xs="24" :md="24">
                <FormItem label="页面地址" prop="Remark">
                    <Input v-model="Form.Data.URL">
                    <Select v-model="Form.Data.UrlGoModuleID" slot="prepend" style="width:120px;text-align: left;" @on-change="Form.SelectModelIDEvent">
                            <Option :value="0" :key="0">自定义</Option>
                            <Option :value="-1" :key="-1">自适应</Option>
                            <Option v-for="item in Form.Data.ChildrenNode" :value="item.id" :key="item.id">{{item.text}}</Option>
                        </Select>
                    </Input>
                </FormItem>
                </Col>

                <Col :xs="8" :md="8">
                <FormItem label="图标" prop="Remark">
                    <Input v-model="Form.Data.Icon"></Input>
                </FormItem>
                </Col>

                <Col :xs="8" :md="8">
                <FormItem label="显示位置" prop="IsShowInMenu">
                    <Select v-model="Form.Data.IsShowInMenu">
                            <Option :value="0" :key="0">不显示</Option>
                            <Option :value="1" :key="1">显示在上边</Option>
                            <Option :value="2" :key="2">显示在左边</Option>
                            <Option :value="3" :key="3">显示在右边</Option>
                        </Select>
                </FormItem>
                </Col>

                <Col :xs="8" :md="8">
                <FormItem label="是否显示左边菜单" prop="IsShowLeftMenu">
                    <Select v-model="Form.Data.IsShowLeftMenu">
                            <Option :value="0" :key="0">不显示</Option>
                            <Option :value="1" :key="1">显示</Option>
                        </Select>
                </FormItem>
                </Col>

                <Col :xs="24" :md="24">
                <FormItem label="页面功能(用空格隔开)" prop="Able">
                    <Input v-model="Form.Data.Able"></Input>
                </FormItem>
                </Col>

                <Col :xs="24" :md="24">

                <FormItem label="数据可见程度配置" prop="DataOptions">
                    <Button class="dataOptionsAddBtn" type="dashed" size="small" icon="md-add" @click="addDataOptions"></Button>
                    <Row :gutter="16" v-for="(option,index) in Form.Data.DataOptions" :key="option.name">
                        <Col span="8" >
                        <Input v-model="option.label"></Input>
                        </Col>
                        <Col span="14" >
                        <Input v-model="option.value"></Input>
                        </Col>
                        <Col span="1" style="padding-left:7px;"><Button @click="removeDataOption(index)" type="dashed" size="small"   icon="md-remove"></Button></Col>
                    </Row>
                </FormItem>
                </Col>
            </Row>
        </Form>
    </Modal>

    <Modal v-model="RollBackWin.IsShow" :loading="RollBackWin.IsLoading" title="恢复" @on-ok="DoRollBack">
        <Select v-model="RollBackWin.FileName">
            <Option v-for="item in FileNameList" :value="item" :key="item">{{ item }}</Option>
        </Select>
    </Modal>

</div>
</template>

<script>
import then from 'thenjs';
import AppFrame from '../../libs/app-frame';
export default {
    data: function() {
        let self = this;
        let MainData = {
            CurSelectNode: null,
            TreeData: []
        };
        let Form = {
            IsShow: false,
            IsLoading: true,
            Data: {},
            OkEvent: function() {
                self.$refs["EditForm"].validate((valid) => {
                    if (valid) {
                        let PostData=JSON.parse(JSON.stringify(Form.Data));
                        let dataOptions=[];
                         PostData.DataOptions.map(function(item){
                             if(item.label!='' && item.value!=''){
                                 dataOptions.push(item);
                             }
                         });
                         if(dataOptions.length>0){
                             PostData.DataOptions=JSON.stringify(PostData.DataOptions);
                         }else{
                             PostData.DataOptions="";
                         }

                        AppFrame.Http.Post("/manage-api/System/system-module/EditModule", PostData, function(err, ret) {

                            if (ret && ret.Result == 1) {
                                var NodeData = self.GetNodeData(ret.Data);
                                if (Form.Data.Type == "Edit") {
                                    self.EditNode(NodeData);
                                } else {
                                    self.AddNode(NodeData);
                                }
                                Form.IsShow = false;
                                self.$Message.success('操作成功');
                            } else {
                                self.$Message.error('操作错误,请重试');
                                Form.IsLoading = false;
                                setTimeout(function() {
                                    Form.IsLoading = true;
                                }, 0);
                            }
                        })
                    } else {
                        Form.IsLoading = false;
                        setTimeout(function() {
                            Form.IsLoading = true;
                        }, 0);
                    }
                });
            },
            CancelEvent: function() {},
            SelectModelIDEvent: function(value) {
                Form.Data.UrlGoModuleID = value;
                if (value == 0) {
                    Form.Data.URL = MainData.CurSelectNode.a_attr.URL;
                } else if (value == -1) {
                    Form.Data.URL = "";
                } else {
                    for (var i in Form.Data.ChildrenNode) {
                        let item = Form.Data.ChildrenNode[i];
                        if (item.id == value) {
                            Form.Data.URL = item.a_attr.URL;
                        }
                    }
                }
            }
        };
        return {
            MainData: MainData,
            CurSelectNode: null,
            Form: Form,
            FileNameList: [],
            RollBackWin: {
                IsShow: false,
                IsLoading: true,
                FileName: ''
            }
        }
    },
    created() {
        this.renderTree();
    },
    methods: {

        GetTreeData(cb) {
            let self = this;
            var _TreeData = [];
            _TreeData.push({
                id: 0,
                text: "系统模块",
                parent: "#",
                icon: "fa fa-folder"
            });

            then(function(defer) {
                AppFrame.Http.Post("/manage-api/system/system-module/getItems", {}, defer);
            }).then(function(defer, ret) {

                if (ret && ret.Result == 1) {
                    defer(null, ret.Data);
                } else {
                    defer({
                        Result: 0
                    });
                }
            }).fin(function(defer, err, ret) {
                if (err) {
                    if (cb) cb(err);
                } else {
                    ret.map(function(item) {
                        var Node = self.GetNodeData(item);
                        _TreeData.push(Node);
                    });
                    if (cb) cb(null, _TreeData);
                }
            })

        },

        GetNodeData(Module) {
            var Node = {
                id: Module.ModuleID,
                parent: Module.ParentID,
                text: Module.Name,
                type: Module.IsParent == 1 ? "parent" : "children",
                a_attr: { //自定义a标签的属性
                    ModuleID: Module.ModuleID,
                    Name: Module.Name,
                    ParentID: Module.ParentID,
                    IsParent: Module.IsParent,
                    Icon: Module.Icon,
                    RoleIDs: Module.RoleIDs,
                    Sort: Module.RoleIDs,
                    URL: Module.URL,
                    UrlGoModuleID: Module.UrlGoModuleID,
                    Able: Module.Able,
                    IsShowInMenu: Module.IsShowInMenu,
                    IsShowLeftMenu: Module.IsShowLeftMenu,
                    Remark: Module.Remark,
                    DataOptions:Module.DataOptions
                }

            }
            return Node;
        },

        RenderEditForm(type, node) {

            var self = this;
            var TreeData = self.MainData.TreeData;
            self.Form.Title = "添加下级菜单";
            var Model = {
                Type: type
            };

            if (node) {
                Model.ParentID = node.a_attr.ParentID;
                Model.ModuleID = node.a_attr.ModuleID;
                Model.Name = node.a_attr.Name;
                Model.URL = node.a_attr.URL;
                Model.Icon = node.a_attr.Icon;
                Model.IsShowInMenu = node.a_attr.IsShowInMenu;
                Model.IsShowLeftMenu = node.a_attr.IsShowLeftMenu;
                Model.Remark = node.a_attr.Remark;
                Model.Able = node.a_attr.Able;
                Model.UrlGoModuleID = node.a_attr.UrlGoModuleID;
                Model.ChildrenNode = [];
                if(node.a_attr.DataOptions && node.a_attr.DataOptions.length>0){
                    Model.DataOptions=JSON.parse(node.a_attr.DataOptions);
                }else{
                     Model.DataOptions=[{label:'',value:''}];
                }

                for (var i = 1; i < TreeData.length; i++) {
                    if (TreeData[i].a_attr.ParentID == Model.ModuleID) {
                        Model.ChildrenNode.push(TreeData[i]);
                    }
                }
                self.Form.Title = "修改 - " + Model.Name;

            } else {
                Model.ParentID = this.MainData.CurSelectNode.id;
                Model.ChildrenNode = [];
                Model.ModuleID = 0;
                Model.Name = "";
                Model.URL = "";
                Model.Icon = "";
                Model.IsShowInMenu = 0;
                Model.IsShowLeftMenu = 1;
                Model.Remark = "";
                Model.Able = "";
                Model.UrlGoModuleID = 0;
                Model.DataOptions=[{label:'',value:''}];
            }
            self.Form.IsShow = true;
            self.Form.Data = Model;

        },

        addDataOptions(){
            this.Form.Data.DataOptions.push({label:'',value:''});
        },

        removeDataOption(index){
            this.Form.Data.DataOptions.splice(index,1);
        },
        renderTree() {
            let self = this;
            /**初始化JsTree */
            function InitSystemModules() {
                let tree = null;

                function initJsTree(TreeData) {

                    $("#SystemModules").on("select_node.jstree", function(e, data) {
                        self.MainData.CurSelectNode = data.node;

                    });

                    $("#SystemModules").on("move_node.jstree", function(e, data) {
                        var TargetNode = tree.get_node(data.parent);
                        var PostData = {
                            CurNodeID: data.node.id,
                            TargetParentID: data.parent,
                            old_parent: data.old_parent,
                            TargetNodeChildrensIDs: TargetNode.children.join(',')
                        }
                        self.CheckIsParent(PostData.TargetParentID);
                        self.CheckIsParent(data.old_parent);
                        AppFrame.Http.Post("/manage-api/system/system-module/MoveNode", PostData, function(BackData) {
                            if (BackData.Result == 0) {
                                self.$Message.success(BackData.Msg);
                            }
                        });
                    });

                    $("#SystemModules").jstree({
                        "core": {
                            "multiple": false,
                            "themes": {
                                "variant": "large",
                                "responsive": false,
                            },
                            // so that create works
                            "check_callback": true,
                            'data': TreeData
                        },
                        "types": {
                            "default": {
                                "icon": " fa fa-link"
                            },
                            "parent": {
                                "icon": " fa fa-bookmark"
                            }
                        },
                        "plugins": ["wholerow", "contextmenu", "dnd", "state", "types"],
                        "state": {
                            "key": "SystemModules"
                        },
                        "contextmenu": {
                            "items": contextmenu
                        }
                    });
                    tree = $.jstree.reference('#SystemModules');
                }

                self.GetTreeData(function(err, TreeData) {
                    self.MainData.TreeData = TreeData;
                    initJsTree(TreeData);
                });

            };

            function contextmenu(node) {
                node = JSON.parse(JSON.stringify(node));
                var items = {
                    edititem: {
                        label: "修改",
                        icon: "glyphicon glyphicon-edit ",
                        action: function() {

                            self.RenderEditForm("Edit", node);
                        }
                    },
                    deleteitem: {
                        label: "删除",
                        icon: "glyphicon glyphicon-remove   ",
                        action: function() {
                            self.DeleteNode(node);
                        }
                    },
                    additem: {
                        label: "添加下级",
                        icon: "glyphicon glyphicon-saved ",
                        action: function() {
                            self.RenderEditForm("Add");
                        }
                    }
                };

                if (node.parent == ("#")) {
                    delete items.lookitem;
                    delete items.deleteitem;
                    delete items.edititem;

                }

                return items;
            };

            InitSystemModules();
        },


        /**
         * 添加 节点
         * @param NodeData
         * @constructor
         */
        AddNode(NodeData) {
            var CurSelectNode = this.MainData.CurSelectNode;
            var tree = $.jstree.reference('#SystemModules');
            tree.create_node(CurSelectNode, NodeData);
            this.CheckIsParent(CurSelectNode.id);
            tree.open_node(CurSelectNode);
            tree.deselect_all();
            tree.select_node(NodeData);
            this.MainData.TreeData.push(NodeData);
        },


        /**
         * 编辑 节点
         * @param NodeData
         * @constructor
         */
        EditNode(NodeData) {
            var CurSelectNode = this.MainData.CurSelectNode;
            CurSelectNode.a_attr = NodeData.a_attr;
            CurSelectNode.text = NodeData.text;
            $.jstree.reference('#SystemModules').set_text(CurSelectNode, NodeData.text);
        },

        /**
         * 删除节点
         * @param NodeData
         * @constructor
         */
        DeleteNode(node) {
            var self = this;
            this.$Modal.confirm({
                title: "提示",
                content: "确实要删除 [" + node.text + "] 吗?",
                loading: true,
                onCancel: () => {
                    self.$Modal.remove();
                },
                onOk: () => {
                    var AllIchildrenIDs = node.children_d;
                    var AllIDs = AllIchildrenIDs.join(',') + "," + node.id;
                    var PostData = {
                        AllIDs: AllIDs,
                        CurNodeID: node.id,
                        CurNodeParentID: node.a_attr.ParentID
                    }

                    var tree = $.jstree.reference('#SystemModules');
                    tree.delete_node(node);
                    self.CheckIsParent(node.a_attr.ParentID);
                    var AllIDsArray = AllIDs.split(",");
                    for (var id in AllIDsArray) {
                        if (AllIDsArray[id] != "") {
                            for (var i = self.MainData.TreeData.length - 1; i >= 0; i--) {
                                if (self.MainData.TreeData[i].id == Number(AllIDsArray[id])) {
                                    self.MainData.TreeData.splice(i, 1);
                                    break;
                                }
                            }
                        }

                    }

                    AppFrame.Http.Post("/manage-api/System/system-module/DelModule", PostData, function(err, BackData) {
                        self.$Modal.remove();
                        if (BackData && BackData.Result == 1) {
                            self.$Message.success('操作成功');
                        } else {
                            self.$Message.error('操作失败');
                        }

                    })


                },
            });
        },


        Publish() {
            var self = this;
            this.$Modal.confirm({
                title: "提示",
                content: "确实要发布吗?",
                loading: true,
                onCancel: () => {
                    self.$Modal.remove();
                },
                onOk: () => {
                    AppFrame.Http.Post("/manage-api/System/system-module/Publish", {}, function(err, ret) {
                        console.log(ret);
                        if (ret && ret.Result == 1) {
                            self.$Message.success('操作成功');
                        } else {
                            self.$Message.error('操作失败');
                        }
                        self.$Modal.remove();
                    })
                }
            });
        },

        RollBack() {
            var self = this;
            this.RollBackWin.IsShow = true;
            AppFrame.Http.Post("/manage-api/system/system-module/GetJsonFile", {}, function(err, ret) {
                if (ret && ret.Result == 1) {
                    self.FileNameList = ret.Data;
                }
            })
        },
        DoRollBack() {
            var self = this;
            var selectFileName = self.RollBackWin.FileName;
            if (selectFileName == '') {
                self.$Message.error('请选择需要恢复的文件');
                self.RollBackWin.IsLoading = false;
                setTimeout(function() {
                    self.RollBackWin.IsLoading = true;
                }, 0);
            };
            AppFrame.Http.Post("/manage-api/system/system-module/RollBack", {
                FileName: selectFileName
            }, function(err, ret) {
                if (ret && ret.Result == 1) {
                    self.RollBackWin.IsShow = false;
                    self.$Message.success('恢复成功');
                }
            })

        },

        /**
         * 检测是否是父级
         * @param NodeID
         * @constructor
         */
        CheckIsParent(NodeID) {
            if (NodeID == 0) return;
            var tree = $.jstree.reference('#SystemModules');
            var ParentNode = tree.get_node(NodeID);
            if (ParentNode) {
                if (ParentNode.children.length > 0) {
                    ParentNode.type = "parent";
                    ParentNode.a_attr.IsParent = 1;
                    tree.set_icon(ParentNode, "fa fa-bookmark ");
                } else {
                    ParentNode.type = "children";
                    ParentNode.a_attr.IsParent = 0;
                    tree.set_icon(ParentNode, "fa fa-link   ");
                }
            }
        }
    }
}
</script>

<style scoped>
.topBtnDiv {
    line-height: 40px;
    background-color: #fff;
}

.dataOptionsAddBtn {
    position: absolute;
    top: -30px;
    right: 0px;
}
</style>
